** Finding elections for which the last election was free and fair

use "$project_path/data/3_cleaned/presidential_elections", clear
merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(election_freefair) nogen
sort Country Year Month
gen last_elec_freefair = election_freefair[_n-1] if Country==Country[_n-1]
keep Country Year Month Type_Election last_elec_freefair
tempfile last_elec_freefair_pres
save `last_elec_freefair_pres'

use "$project_path/data/3_cleaned/parliamentary_elections", clear
merge m:1 Country Year using "$project_path/data/2_intermediary/outcomes/outcomes_vdem.dta", keep(master match) keepusing(election_freefair) nogen
sort Country Year Month
gen last_elec_freefair = election_freefair[_n-1] if Country==Country[_n-1]
keep Country Year Month Type_Election last_elec_freefair
append using `last_elec_freefair_pres'
tempfile last_elec_freefair
save `last_elec_freefair'

** Regressions

log using "$project_path/output/appendix_tables/Appendix_Table_D9.smcl", replace

use "$project_path/data/4_regdata/regdata", clear
merge 1:1 Country Year Month Type_Election using `last_elec_freefair', keep(master match) nogen

rdrobust diff_m1_chix_econ runvar if last_elec_freefair==1, all
rdrobust std_diff_m1_growth_gdpc_penn runvar if last_elec_freefair==1, all
rdrobust mstd_diff_m1_inflation_imf runvar if last_elec_freefair==1, all
rdrobust mstd_diff_m1_unemployment_ilo runvar if last_elec_freefair==1, all
rdrobust std_diff_m1_trade_wb runvar if last_elec_freefair==1, all
rdrobust std_diff_m1_hdi runvar if last_elec_freefair==1, all
rdrobust std_diff_m1_democracy_index runvar if last_elec_freefair==1, all
rdrobust diff_m1_general_chix runvar if last_elec_freefair==1, all

log close


** Building .tex table

#delimit ;
local outcomes  
		diff_m1_chix_econ 
		std_diff_m1_growth_gdpc_penn 
		mstd_diff_m1_inflation_imf 
		mstd_diff_m1_unemployment_ilo 
		std_diff_m1_trade_wb 
		std_diff_m1_hdi 
		std_diff_m1_democracy_index 
		diff_m1_general_chix
;
#delimit cr		

local model_count : word count `outcomes'

	// Initialize matrix of results and define value labels
	local ncols = `model_count'*2
	local nrows = 6
	//Prepare matrix of coefficients and other statistics
	mat Coefs = J(`nrows', `ncols', .)
		

//inizialize indices
local i = 0
local pval_col = `model_count'
foreach v in `outcomes'{
	local ++i 
	local ++pval_col
	rdrobust `v' runvar if last_elec_freefair==1, all
	
	//Store estimates and stats
	local b_`i': di %5.3f e(tau_cl)
	local se_`i': di %5.3f e(se_tau_rb)
	local p_`i': di %5.3f e(pv_rb)
	local N_`i': di %6.0f e(N)
	loca N_eff_`i': di %6.0f e(N_h_l) + e(N_h_r)
	local bw_`i': di %5.1f e(h_r)
	
	
	mat Coefs[1,`i'] = `b_`i''
	mat Coefs[2,`i'] = `se_`i''
	mat Coefs[3,`i'] = `p_`i''	
	mat Coefs[4,`i'] = `N_`i''
	mat Coefs[5,`i'] = `N_eff_`i''
	mat Coefs[6,`i'] = `bw_`i''
	
	mat Coefs[1,`pval_col'] = `p_`i''
	


}
mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	input str22 varname 
	"El. turn."
	"SE"
	"p-val"
	"N"
	"N eff."
	"Band."
	
	replace varname = "" if varname == "SE"
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`model_count'{
		rename Coefs`n' Model`n'
	}
	
	//Cols where we store pvalues
	local n_min = `model_count' + 1
	local n_max = `model_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}

	label var varname ""
	label var Model1 "\textbf{Econ. perf.}"
	label var Model2 "GDP p.c. gr."
	label var Model3 "(Minus) Inflation"
	label var Model4 "(Minus) Unemp."
	label var Model5 "Trade"
	label var Model6 "\textbf{HDI}"
	label var Model7 "\textbf{Democ.}"
	label var Model8 "\textbf{General index}"
		
	// Convert to string and add options
	forvalues i = 1/`model_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	
		replace Model`i' = "[" + Model`i' + "]" if varname == "p-val" & Model`i' !=""	
		//Remove decimals to N obs
		replace Model`i' = substr(Model`i', 1, strpos(Model`i', ".")-1) if varname == "N"
		replace Model`i' = substr(Model`i', 1, strpos(Model`i', ".")-1) if varname == "N eff."
		
		replace Model`i' = substr(Model`i', 1, strpos(Model`i', ".")+1) if varname == "Band."

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/8{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
		
	}

	local title "Robustness to using only elections following a free and fair election"
	local label_key "tab:index_components_robustness_last_freefair"
	local output "$project_path/output/appendix_tables/Appendix_Table_D9.tex"
	local header "& (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8)"
	local footnote = "\emph{Notes}: This table reports results for the statistical procedure of Table \ref{tab:index_components_baseline}, restricting the sample to elections for which the previous election of the same type was coded as free and fair by V-Dem."

	texsave using "`output'", replace varlabels frag nofix hlines(3) location(h) ///
							  title("`title'")  ///
							  footnote("`footnote'") ///
							  marker("`label_key'") ///
							  headerlines("`header'")
			




